import 'package:async/src/result/result.dart';
import 'package:boss/models/store_area.dart';
import 'package:boss/models/store_table.dart';
import 'package:boss/provider/table_provider.dart';
import 'package:boss/textStyle/text_style.dart';
import 'package:boss/ui/page/miniProgram/miniProgramQrConfig/mini_program_qr_config_page.dart';
import 'package:boss/ui/page/tableManagement/page/plusBatchTable/plus_batch_table_page.dart';
import 'package:boss/ui/page/tableManagement/page/tableDetail/table_detail_page.dart';
import 'package:boss/ui/widget/alert/alert.dart';
import 'package:boss/ui/widget/button/fixed_bottom_double_btn.dart';
import 'package:boss/ui/widget/button/radius_button.dart';
import 'package:boss/ui/widget/center_title_app_bar.dart';
import 'package:boss/ui/widget/image/base_image.dart';
import 'package:boss/ui/widget/label_button.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:boss/ui/widget/shadow_radius_card.dart';
import 'package:flutter/material.dart';
import 'package:hi_common/hi_common.dart';
import 'package:provider/provider.dart';
import 'package:router/annotation.dart';
import 'package:boss/ui/widget/radioList/radio.dart' as radio;

@RouterConfig(MiniProgramTableConfigPage.pageName)
class MiniProgramTableConfigPage extends StatefulWidget {
  static const pageName = '/MiniProgramTableConfigPage';

  @override
  _MiniProgramTableConfigPageState createState() => _MiniProgramTableConfigPageState();
}

class _MiniProgramTableConfigPageState extends BaseState<MiniProgramTableConfigPage> {
  _MiniProgramTableConfigPageState() : super(MiniProgramTableConfigPage.pageName);

  bool isEditing = false;

  String get actionText => isEditing ? '取消' : '编辑';

  int stepView = 1;

  List<int> selectedTableIds = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CenterTitleAppBar(
        title: '选择要生成的桌台',
        actions: [
          if (stepView == 1)
            LabelButton(
              title: actionText,
              padding: EdgeInsets.symmetric(horizontal: 2, vertical: 1),
              textStyle: TextStyleConstant().blue_28,
              onTap: editSeat,
            )
        ],
      ),
      body: Loader<List<StoreArea>>(
        loadTask: loadTask,
        builder: (context) {
          return Consumer<TableProvider>(builder: (context, provider, _) {
            if (provider.storeAreas.isEmpty) {
              return buildEmpty();
            }

            return buildContent(provider.storeAreas);
          });
        },
      ),
    );
  }

  buildEmpty() {
    return Center(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          BaseImage(
            'assets/image/empty_icon.png',
            width: 280.w,
            height: 240.w,
          ),
          Text('您还没有添加座位', style: TextStyleConstant().normal_4_26),
          RadiusButton(
            title: '批量添加座位',
            margin: EdgeInsets.only(top: 100.w),
            width: 590.w,
            height: 80.w,
            onTap: nextBatchPlusTable,
          ),
        ],
      ),
    );
  }

  Widget buildContent(List<StoreArea> storeAreaList) {
    return Column(
      children: [
        Expanded(
          child: CustomScrollView(
            slivers: [
              for (final storeArea in storeAreaList) ...buildAreaRow(storeArea),
            ],
          ),
        ),
        buildFooter(storeAreaList),
      ],
    );
  }

  List<Widget> buildAreaRow(StoreArea storeArea) {
    return [
      SliverToBoxAdapter(
        child: Container(
          height: 90.w,
          margin: EdgeInsets.only(left: 30.w),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(storeArea.areaName, style: TextStyleConstant().normal_1_32),
              if (isEditing)
                LabelButton(
                  title: '+添加桌台',
                  padding: EdgeInsets.symmetric(horizontal: 30.w, vertical: 4),
                  onTap: () => openPlusTable(storeArea),
                ),
            ],
          ),
        ),
      ),
      SliverPadding(
        padding: EdgeInsets.symmetric(horizontal: 20.w),
        sliver: SliverGrid(
          delegate: SliverChildBuilderDelegate(
            (context, index) {
              final current = storeArea.storeTableList[index];

              return buildTableItem(current);
            },
            childCount: storeArea.storeTableList.length,
          ),
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 4, childAspectRatio: 11 / 9),
        ),
      ),
    ];
  }

  Widget buildTableItem(StoreTable storeTable) {
    final isSelected = selectedTableIds.any((element) => element == storeTable.tableId);

    return Stack(
      children: [
        Padding(
          padding: EdgeInsets.all(10.w),
          child: GestureDetector(
            onTap: () => toggleSelectedTable(storeTable.tableId),
            child: ShadowRadiusCard(
              width: double.infinity,
              height: double.infinity,
              padding: EdgeInsets.symmetric(horizontal: 20.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  Text(
                    storeTable.tableName,
                    style: TextStyleConstant().normal_1_36,
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  Text('${storeTable.maxPerson}人', style: TextStyleConstant().normal_2_26),
                ],
              ),
            ),
          ),
        ),
        if (isSelected) buildSeatItemBadge('assets/image/select_blue_icon.png'),
        if (isEditing) buildSeatItemBadge('assets/image/close_icon.png', onTap: () => deleteTable(storeTable)),
      ],
    );
  }

  Widget buildSeatItemBadge(String icon, {VoidCallback onTap}) {
    return Positioned(
      top: 0,
      right: 0,
      child: GestureDetector(
        onTap: onTap,
        behavior: HitTestBehavior.translucent,
        child: Padding(
          padding: EdgeInsets.only(left: 4, bottom: 4),
          child: BaseImage(
            icon,
            width: 30.w,
            height: 30.w,
          ),
        ),
      ),
    );
  }

  buildFooter(List<StoreArea> storeAreaList) {
    int totalTableCount = 0;
    storeAreaList.forEach((element) {
      totalTableCount += element.storeTableList.length;
    });

    final isSelectedAll = totalTableCount == selectedTableIds.length;

    return Container(
      height: 120.w + MediaQuery.of(context).padding.bottom,
      padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom, left: 30.w, right: 30.w),
      alignment: Alignment.center,
      decoration: BoxDecoration(
        color: Colors.white,
        boxShadow: [DEFAULT_SHADOW],
      ),
      child: Row(
        children: [
          Expanded(
            flex: 3,
            child: GestureDetector(
              onTap: () => toggleSelectedAllTable(!isSelectedAll),
              behavior: HitTestBehavior.translucent,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Row(
                    children: [
                      radio.Radio(
                        isSelected: isSelectedAll,
                        width: 30.w,
                        height: 30.w,
                      ),
                      Container(
                        child: Text(
                          '全选',
                          style: TextStyleConstant().normal_1_28,
                        ),
                        margin: EdgeInsets.only(left: 10.w),
                      ),
                    ],
                  ),
                  Container(
                    child: Text(
                      '已选中${selectedTableIds.length}个座位',
                      style: TextStyleConstant().normal_3_24,
                    ),
                    margin: EdgeInsets.only(left: 5.w, top: 5.w),
                  ),
                ],
              ),
            ),
          ),
          Expanded(
            flex: 7,
            child: RadiusButton(
              title: '下一步，定制二维码',
              onTap: nextPage,
              radius: 10,
              enabled: selectedTableIds.length > 0,
            ),
          ),
        ],
      ),
    );
  }

  Future<Result<List<StoreArea>>> loadTask() {
    final tableProvider = Provider.of<TableProvider>(context, listen: false);
    return tableProvider.initData();
  }

  void nextBatchPlusTable() {
    Navigator.pushNamed(context, PlusBatchTablePage.pageName);
  }

  void editSeat() {
    setState(() {
      isEditing = !isEditing;
    });
  }

  void nextPage() {
    Navigator.pushNamed(context, MiniProgramQrConfigPage.pageName);
  }

  toggleSelectedTable(int tableId) {
    setState(() {
      if (selectedTableIds.contains(tableId)) {
        selectedTableIds.remove(tableId);
      } else {
        selectedTableIds.add(tableId);
      }
    });
  }

  toggleSelectedAllTable(bool isSelectAll) {
    setState(() {
      selectedTableIds = [];

      if (isSelectAll) {
        final tableProvider = Provider.of<TableProvider>(context, listen: false);

        tableProvider.storeAreas.forEach((storeArea) {
          selectedTableIds.addAll(storeArea.storeTableList.map((table) => table.tableId));
        });
      }
    });
  }

  deleteTable(StoreTable storeTable) {
    showAlert(
      context,
      content: '确认删除该桌台？',
      onConfirm: (ctx) {
        Navigator.pop(ctx);

        final tableProvider = Provider.of<TableProvider>(context, listen: false);
        tableProvider.deleteStoreTable(storeTable);

        if (selectedTableIds.contains(storeTable.tableId)) {
          setState(() {
            selectedTableIds.remove(storeTable.tableId);
          });
        }
      },
      onCancel: (context) {
        Navigator.pop(context);
      },
    );
  }

  void openPlusTable(StoreArea storeArea) {
    Navigator.pushNamed(context, TableDetailPage.pageName, arguments: {
      'storeArea': storeArea,
    });
  }
}
